const Promise = require('bluebird');

/**
 * 保存淘宝联盟订单
 */
const statusMap = {'订单付款': 1, '订单结算': 1, '订单失效': 1};
exports.save = function ({body, user_id}, {models: {Users, UserOrders, TaokeOrders, TaokeOrdersLogs, sequelize}, spider, config, wechatInstance}) {
    let {auctionId, taobaoTradeParentId} = body;
    if (!auctionId || !taobaoTradeParentId) {
        return {success: false, messsage: '参数错误'};
    }

    let getOrderUrl = function () {
        return config.domain + '/partner_orders?taobaoTradeParentId=' + taobaoTradeParentId;
    }

    return Users.findOne({where: {id: user_id, level: 'Partner'}}).then(function (partner) {
        if (!partner) {
            return {success: false, messsage: '没有权限'};
        }
        return TaokeOrders.findOne({
            where: {
                auctionId: auctionId,
                taobaoTradeParentId: taobaoTradeParentId
            }
        }).then(function (order) {
            if (order) {
                if (order.payStatus === body.payStatus) {
                    console.error('订单状态没有变', body);
                    return {success: true, exist: true};
                }
                if (order.payStatus === '订单失效') {
                    console.error('失效订单状态不能再更新了', body);
                    return {success: true, exist: true, messsage: '失效订单状态不能再更新了'};
                }
                if (order.payStatus === '订单结算' && body.payStatus === '订单付款') {
                    console.error('订单结算不能再转订单付款状态', body);
                    return {success: true, exist: true, messsage: '订单结算不能再转订单付款状态'};
                }

                if (!statusMap[body.payStatus]) {
                    wechatInstance.shopWebApi.sendText(partner.openid, '无效订单状态,' + body.payStatus, function (err) {
                        if (err) {
                            console.error('\n', err.stack || err.message);
                        }
                    });
                    return {success: true, messsage: '无效订单状态'};
                }

                return TaokeOrders.update(body, {where: {id: order.id}}).then(function (result) {
                    if (result[0]) {
                        TaokeOrdersLogs.create({
                            opt: 'StatusUpdate',
                            reference: order.id,
                            ext_data: JSON.stringify({
                                from: order.payStatus,
                                fromBy: order.postBy,
                                to: body.payStatus,
                                toBy: body.postBy
                            }),
                            user_id: user_id
                        });

                        if (body.payStatus === '订单失效') {
                            //is_back
                            TaokeOrders.backV2(order);

                            if (partner.notifyAllOrder && body.postBy != 'Import') {
                                wechatInstance.shopWebApi.sendText(partner.openid, order.auctionTitle + '\n\n状态更新:' + order.payStatus + '-' + body.payStatus + '\n\n' + getOrderUrl(), function (err) {
                                    if (err) {
                                        console.error('\n', err.stack || err.message);
                                    }
                                });
                            }
                        }
                        if (body.payStatus === '订单结算') {
                            //is_settle
                            TaokeOrders.settleV2(order);
                        }

                        return {success: true, update: true};
                    }

                    return {success: false, update: false, messsage: '状态更新失败'};
                });
            } else {
                // return spider.getGoodsByAuctionId({id: auctionId}).then(function (goods) {
                //     if (goods) {
                //         body.auctionUrl = goods.auctionUrl;
                //         body.pictUrl = goods.pictUrl;
                //     }
                //
                //
                // });

                let sql = "select * from Users where level in('Agency', 'Partner') and " +
                  "((mediumId = :mediumId and adPositionId = :adPositionId) or (domain_mediumId = :mediumId and domain_adPositionId = :adPositionId) or (qun_mediumId = :mediumId and qun_adPositionId = :adPositionId)) limit 0,1";
                return sequelize.query(sql, {
                    type: sequelize.QueryTypes.SELECT,
                    replacements: {mediumId: body.mediumId, adPositionId: body.adPositionId}
                }).then(function (rows) {
                    return rows && rows[0];
                }).then(function (agency) {
                    if (agency && agency.inviter_id) {
                        return Users.findOne({
                            where: {id: agency.inviter_id, level: ['Agency', 'Partner']},
                            attributes: ['id']
                        }).then(function (inviterAgency) {
                            return {agency: agency, inviterAgency: inviterAgency}
                        });
                    }
                    return {agency: agency};
                }).then(function ({agency, inviterAgency}) {
                    if (agency) {
                        if (agency.agency_scale > 0) {
                            body.agency_id = agency.id;
                            body.agency_amount = (parseFloat(body.feeString) * agency.agency_scale / 100).toFixed(2);
                        }
                        if (inviterAgency && agency.inviter_agency_scale > 0) {
                            body.inviter_agency_id = inviterAgency.id;
                            body.inviter_agency_amount = (parseFloat(body.feeString) * agency.inviter_agency_scale / 100).toFixed(2);
                        }

                        if (agency.order_return_scale > 0) {
                            body.pay_amount = (parseFloat(body.feeString) * agency.order_return_scale / 100).toFixed(2);
                        }
                        if (agency.inviter_scale > 0) {
                            body.inviter_pay_amount = (parseFloat(body.feeString) * agency.inviter_scale / 100).toFixed(2);
                        }
                    }

                    body.partner_id = user_id;
                    return TaokeOrders.create(body).then(function (taokeOrder) {
                        if (taokeOrder.payStatus != '订单失效') {
                            UserOrders.findOne({where: {taobaoTradeParentId: taobaoTradeParentId}}).then(function (userOrder) {
                                if (!userOrder) {
                                    return;
                                }
                                return Users.findOne({where: {id: userOrder.user_id}}).then(function (user) {
                                    return UserOrders.update({status: 'Related'}, {where: {id: userOrder.id}}).then(function () {
                                        let updateData = {
                                            user_id: user.id,
                                            // pay_amount: spider.getRealFanli({
                                            //     fee: parseFloat(taokeOrder.feeString),
                                            //     user: user,
                                            //     agency: agency
                                            // }),
                                            status: 'Related'
                                        }
                                        if (user.inviter_id) {
                                            // && agency.inviter_scale > 0
                                            updateData.inviter_id = user.inviter_id;
                                            // updateData.inviter_pay_amount = (parseFloat(taokeOrder.feeString) * agency.inviter_scale / 100).toFixed(2);
                                        }
                                        return TaokeOrders.update(updateData, {where: {id: taokeOrder.id}}).then(function () {
                                            return TaokeOrders.amountV2(taokeOrder.id);
                                        });
                                    });
                                });
                            });

                            if (partner.notifyAllOrder && body.postBy != 'Import') {
                                wechatInstance.shopWebApi.sendText(partner.openid, taokeOrder.auctionTitle + '\n\n新订单:' + body.payStatus + '\n\n' + getOrderUrl(), function (err) {
                                    if (err) {
                                        console.error('\n', err.stack || err.message);
                                    }
                                });
                            }
                        }

                        return {success: true, create: true};
                    });
                });
            }
        });
    });
}

/**
 * 操作订单
 */
exports.refundSave = function ({body, user_id}, {models: {Users, TaokeRefunds, TaokeRefundsLogs, TaokeOrders, TaokeOrdersLogs}, spider, config, wechatInstance}) {
    let {tbTradeParentId, tbTradeId, tbAuctionTitle, showRefundStatus} = body;

    return Users.findOne({where: {id: user_id, level: 'Partner'}}).then(function (partner) {
        if (!partner) {
            return {success: false, messsage: '没有权限'};
        }
        return TaokeRefunds.findOne({
            where: {
                tbTradeParentId: tbTradeParentId,
                tbTradeId: tbTradeId
            }
        }).then(function (taokeRefund) {
            if (taokeRefund) {
                if (showRefundStatus == taokeRefund.showRefundStatus) {
                    return {success: true, messsage: '状态已经存在'};
                }
                return TaokeRefunds.update({showRefundStatus: showRefundStatus}, {where: {id: taokeRefund.id}}).then(function () {
                    TaokeRefundsLogs.create({
                        opt: 'StatusUpdate',
                        reference: taokeRefund.id,
                        ext_data: JSON.stringify({from: taokeRefund.showRefundStatus, to: showRefundStatus}),
                        user_id: user_id
                    });
                    return {success: true, messsage: '状态更新'};
                });
            }

            return TaokeRefunds.create(body).then(function (newTaokeRefund) {
                TaokeRefundsLogs.create({
                    opt: 'Create',
                    reference: newTaokeRefund.id,
                    ext_data: JSON.stringify({to: showRefundStatus}),
                    user_id: user_id
                });

                return TaokeOrders.findOne({
                    where: {
                        taobaoTradeParentId: tbTradeParentId,
                        auctionTitle: tbAuctionTitle
                    }
                }).then(function (taokeOrder) {
                    if (!taokeOrder) {
                        return {success: true, messsage: '创建成功，未关连'};
                    }
                    return TaokeRefunds.update({
                        tbAuctionId: taokeOrder.auctionId,
                        partner_id: taokeOrder.partner_id,
                        agency_id: taokeOrder.agency_id,
                        inviter_agency_id: taokeOrder.inviter_agency_id,
                        inviter_id: taokeOrder.inviter_id,
                        user_id: taokeOrder.user_id,
                        status: 'Related'
                    }, {where: {id: newTaokeRefund.id}}).then(function () {

                        if (taokeOrder.payStatus === '订单失效') {
                            return {success: true, messsage: '订单已经是失效状态'};
                        }
                        return TaokeOrders.update({payStatus: '订单失效'}, {where: {id: taokeOrder.id}}).then(function (result) {
                            if (result[0]) {
                                TaokeOrdersLogs.create({
                                    opt: 'StatusUpdate',
                                    reference: taokeOrder.id,
                                    ext_data: JSON.stringify({
                                        from: taokeOrder.payStatus,
                                        to: '订单失效'
                                    }),
                                    user_id: user_id
                                });

                                TaokeOrders.backV2(taokeOrder).then(function (result) {
                                    if (result.success) {
                                        TaokeRefunds.update({is_back: 1}, {where: {id: newTaokeRefund.id}});
                                    }
                                });
                                return {success: true, update: true};
                            }
                            return {success: true, update: false};
                        });
                    });
                });
            });
        });
    });
}

/**
 * 操作订单
 */
exports.operate = function ({body, user_id}, {models: {Users, UserOrders, TaokeOrders, TaokeOrdersLogs}, spider, config, wechatInstance}) {
    let {opt, id} = body;
    if (!opt || !id) {
        return {success: false, messsage: '参数错误'};
    }
    return Users.findOne({where: {id: user_id, level: 'Partner'}}).then(function (partner) {
        if (!partner) {
            return {success: false, messsage: '不是合伙人'};
        }
        return TaokeOrders.findOne({where: {id: id}}).then(function (taokeOrder) {
            if (taokeOrder.partner_id != partner.id && taokeOrder.tao_user != partner.tao_user) {
                return {success: false, messsage: '没有权限'};
            }
            if (opt === 'payed') {
                if (TaokeOrders.payedCheck(taokeOrder)) {
                    return TaokeOrders.payedV2(taokeOrder);
                } else {
                    return {success: false, messsage: '确认返款失败'};
                }
            }
            if (opt === 'back') {
                if (taokeOrder.payStatus === '订单失效') {
                    return {success: false, messsage: '订单已经是失效状态'};
                }
                return TaokeOrders.update({payStatus: '订单失效'}, {where: {id: taokeOrder.id}}).then(function (result) {
                    if (result[0]) {
                        TaokeOrdersLogs.create({
                            opt: 'StatusUpdate',
                            reference: taokeOrder.id,
                            ext_data: JSON.stringify({
                                from: taokeOrder.payStatus,
                                to: '订单失效'
                            }),
                            user_id: user_id
                        });

                        TaokeOrders.backV2(taokeOrder);
                        return {success: true, update: true};
                    }
                    return {success: true, update: false};
                });
            }
            if (opt === 'sham') {
                if (taokeOrder.is_sham) {
                    return {success: false, messsage: '订单已经标记欺诈'};
                } else {
                    return TaokeOrders.shamV2(taokeOrder);
                }
            }
            if (opt === 'cancel_sham') {
                if (!taokeOrder.is_sham) {
                    return {success: false, messsage: '订单没有标记欺诈'};
                } else {
                    return TaokeOrders.cancelShamV2(taokeOrder);
                }
            }

            return {success: true};
        });
    });
}

/**
 * 代理订单统计
 */
exports.ordersAnalyse = function ({query, user_id}, {models: {Users, TaokeOrders}, cache: {settings, dicts}, controller}) {
    return Users.findOne({where: {id: query.user_id || user_id, level: ['Partner', 'Agency']}}).then(function (user) {
        if (!user) {
            return {success: false, messsage: '不是代理'};
        }
        return TaokeOrders.analyseV2({agency_id: user_id}).then(function (data) {
            return {success: true, data: data};
        });
    });
}

/**
 * 代理冻结统计
 */
exports.ordersFrozen = function ({query, user_id}, {models: {Users, TaokeOrders}, cache: {settings, dicts}, controller}) {
    return Users.findOne({where: {id: query.user_id || user_id, level: ['Partner', 'Agency']}}).then(function (user) {
        if (!user) {
            return {success: false, messsage: '不是代理'};
        }
        return TaokeOrders.agencyFrozenV2(query.user_id || user_id).then(function (data) {
            return {success: true, data: data};
        });
    });
}
